package com.example.carrierapp.ui.main.dispatch.detail.history

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import butterknife.ButterKnife
import com.example.carrierapp.base.MVPBaseFragment
import com.example.carrierapp.bean.RowsBean
import com.example.carrierapp.bean.dispatch.CarFreeBean
import com.example.carrierapp.bean.dispatch.DispatchHistoryBean
import com.example.carrierapp.config.ConstValue
import com.example.carrierapp.config.gone
import com.example.carrierapp.config.mStartActivity
import com.example.carrierapp.config.show
import com.example.carrierapp.ui.adapter.CommonRecyclerAdapter
import com.example.carrierapp.ui.adapter.DispatchHistoryAdatpter
import com.example.carrierapp.ui.dialog.DispatchAgainDialog
import com.example.carrierapp.ui.dialog.DispatchModifyDialog
import com.example.carrierapp.ui.main.dispatch.search.DispatchSearchActivity
import com.example.carrierapp.ui.main.waybill.details.WaybillDetailsActivity
import com.example.carrierapp.ui.view.recycleview.HorizontalDividerDecoration
import com.example.carrierapp.ui.view.recycleview.WrapContentManager
import com.example.carrierapp.ui.view.recycleview.XRecyclerView
import com.example.carrierapp.util.*
import com.example.carrierapp.viewmodel.itemmodel.ItemDispatchHistoryModel
import com.example.lb.fingerdemo.R
import kotlinx.android.synthetic.main.fragment_dispatch_history.*
import kotlinx.android.synthetic.main.item_dispatch_history_new.view.*
import kotlinx.android.synthetic.main.layout_recycleview.*
import kotlinx.android.synthetic.main.layout_search_bar.*

/**
 * 调度 调度记录
 */
class DispatchHistoryFragment : MVPBaseFragment<DispatchHistoryContract.View, DispatchHistoryPresenter>(), DispatchHistoryContract.View, XRecyclerView.LoadingListener, DispatchAgainDialog.OnVolumeClickListeber, DispatchModifyDialog.OnVolumeClickListeber {

    private var mPage = 0
    private var mFilter = ""
    private var mLoadMore: Boolean = false
    private var mId: Int = 0
    private var mDispatchAgainDialog: DispatchAgainDialog? = null
    private var mClickHistoryInfo: DispatchHistoryBean.DispatchHistoryInfo? = null
    private var mDispatchModifyDialog: DispatchModifyDialog? = null
    private var mShowOpera: Boolean = false
    private val adapter by lazy {
        CommonRecyclerAdapter<ItemDispatchHistoryModel>(context, R.layout.item_dispatch_history_new) { v, t, _ ->
            v.to_details.setOnClickListener {
                if (t?.id == 0) {
                    ToastUtils.showCenterToast(context, "运单暂未创建，请稍后再试！")
                } else {
                    mStartActivity(WaybillDetailsActivity::class.java, Pair("id", t?.id), Pair("state", t?.billState))
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mId = arguments?.getInt(ConstValue.ID, 0) ?: 0
        mShowOpera = arguments?.getBoolean(ConstValue.SHOW_OPERA, false) ?: false
    }

    override fun getLayout(): Int {
        return R.layout.fragment_dispatch_history
    }

    override fun initView() {
        super.initView()
        ButterKnife.bind(this, mRootView)
        initRecycleView()
        et_dispatch_search?.hint = "输入姓名/电话/车牌号"
    }

    override fun initData() {
        super.initData()
//        showProgress()
        mPresenter.attachView(this)
        mPresenter.getDeliveryHistoryDetail(mId, mFilter, mPage)
    }

    private fun initRecycleView() {
        val mLinearLayoutManager = WrapContentManager(context, LinearLayoutManager.VERTICAL, false)
        recycler_view?.layoutManager = mLinearLayoutManager
        recycler_view?.addItemDecoration(HorizontalDividerDecoration(context, R.drawable.divider_horizontal_10_f3f6fa, DisplayUtil.dip2px(context, 10f)))
        recycler_view?.setHasFixedSize(true)
        recycler_view?.setLoadingMoreEnabled(true)
        recycler_view?.setPullRefreshEnabled(true)
        recycler_view?.setLoadingListener(this)
        recycler_view?.refreshComplete()
        recycler_view?.loadMoreComplete()

        recycler_view?.adapter = adapter
    }

    override fun onRefresh() {
        mFilter = ""
        mPage = 0
        mPresenter.getDeliveryHistoryDetail(mId, mFilter, mPage)
        mLoadMore = false
    }

    override fun onLoadMore() {
        mPage++
        mPresenter.getDeliveryHistoryDetail(mId, mFilter, mPage)
        mLoadMore = true
    }

    override fun initEvent() {
        super.initEvent()
        ib_clear.setOnClickListener { et_dispatch_search?.setText("") }
        et_dispatch_search?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

                if (!TextUtils.isEmpty(et_dispatch_search?.text.toString().trim { it <= ' ' })) {
                    ib_clear?.visibility = View.VISIBLE
                } else {
                    ib_clear?.visibility = View.GONE
                }
                mLoadMore = false
                mFilter = et_dispatch_search?.text.toString().trim { it <= ' ' }
                mPage = 0
                mPresenter.getDeliveryHistoryDetail(mId, mFilter, mPage)
            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }

    override fun createPresenter(): DispatchHistoryPresenter {
        return DispatchHistoryPresenter(context)
    }

    override fun getDeliveryHistoryDetailSuccess(bean: RowsBean<ItemDispatchHistoryModel>) {
        dismissProgress()
        LogUtil.d("DispatchNoFragment-getDispatchListSuccess-$bean")
        bean.items?.let {
            ll_empty.gone()
            if (mLoadMore) {
                recycler_view.loadMoreComplete()
                adapter.insertData(it)
            } else {
                recycler_view.refreshComplete()
                adapter.refresh(it)
            }
            recycler_view.setNoMore(it.size < 10)
        } ?: let {
            recycler_view.setNoMore(true)
            if (mLoadMore) {
                recycler_view.loadMoreComplete()
                ll_empty.gone()
            } else {
                recycler_view.refreshComplete()
                adapter.clear()
                ll_empty.show()
            }
        }
    }

    override fun getDeliveryHistoryDetailFailde(msg: String) {
        dismissProgress()
        LogUtil.d("DispatchHistoryFragment-getDeliveryHistoryDetailFailde-$msg")
        ToastUtils.showCenterToast(msg, context)
        if (recycler_view != null) {
            recycler_view?.loadMoreComplete()
            recycler_view?.refreshComplete()
        }
        ll_empty?.visibility = if (adapter.itemCount == 0) View.VISIBLE else View.GONE
    }

    override fun dispatchAgainSuccess(bean: String) {
        dismissProgress()
        ToastUtils.showCenterToast(context, "再次调度成功")
        onRefresh()
        if (mDispatchAgainDialog != null && mDispatchAgainDialog?.isShowing == true) {
            mDispatchAgainDialog?.dismiss()
        }
    }

    override fun dispatchAgainDetailFailde(msg: String) {
        dismissProgress()
        ToastUtils.showCenterToast(context, msg)
    }

    override fun dispatchModifySuccess(bean: String) {
        dismissProgress()
        ToastUtils.showCenterToast(context, "修改成功")
        onRefresh()
        //        mAdapter.updataItemData(mClickHistoryInfo);
        if (mDispatchModifyDialog != null && mDispatchModifyDialog?.isShowing == true) {
            mDispatchModifyDialog?.dismiss()
        }
    }

    override fun dispatchModifyFailde(msg: String) {
        dismissProgress()
        ToastUtils.showCenterToast(context, msg)
    }

//    override fun onModifyClick(info: DispatchHistoryBean.DispatchHistoryInfo) {
//        mClickHistoryInfo = info
//        if (mDispatchModifyDialog == null) {
//            mDispatchModifyDialog = DispatchModifyDialog(context)
//            mDispatchModifyDialog?.setOnVolumeClickListeber(this)
//        }
//        mDispatchModifyDialog?.showDialog(info.driverName, info.isMultiple, info.carNumber, info.carId, info.expectedWeight)
//    }

//    override fun onAgainClick(info: DispatchHistoryBean.DispatchHistoryInfo) {
//        mClickHistoryInfo = info
//        if (mDispatchAgainDialog == null) {
//            mDispatchAgainDialog = DispatchAgainDialog(context)
//            mDispatchAgainDialog?.setOnVolumeClickListeber(this)
//        }
//        mDispatchAgainDialog?.showDialog(info.driverName, info.driverPhone, info.carId, info.carNumber)
//    }
//
//    override fun onDetailClick(info: DispatchHistoryBean.DispatchHistoryInfo) {
//        LogUtil.d("DispatchHistoryFragment-onDetailClick-" + info.isMultiple + "-" + info.waybillId + "-" + info.dispatchId)
//        if (info.isMultiple) {
//
//        } else {
//            if (info.dispatchId == 0) {
//                ToastUtils.showCenterToast(context, "运单暂未创建，请稍后再试！")
//            } else {
//                ActivityUtil.startWaybillYesDetail(context, info.dispatchId)
//            }
//        }
//    }

    override fun onAgainClick(carId: Int, volume: String) {
        showProgress()
        mPresenter.dispatchAgain(carId, mClickHistoryInfo?.waybillId, volume, mClickHistoryInfo?.driverId)
    }

    override fun onModifyClick(carNum: String, carId: Int, volume: String, isMo: Boolean, times: String, deadLine: String) {
        showProgress()
        mClickHistoryInfo?.carId = carId
        mClickHistoryInfo?.expectedWeight = if (TextUtils.isEmpty(volume)) 0.0 else java.lang.Double.valueOf(volume)
        mClickHistoryInfo?.isMultiple = isMo
        mClickHistoryInfo?.limitCount = if (TextUtils.isEmpty(times)) 0 else Integer.valueOf(times)
        if (!TextUtils.isEmpty(deadLine)) {
            mClickHistoryInfo?.validityPeriod = deadLine
        }
        if (!TextUtils.isEmpty(carNum)) {
            mClickHistoryInfo?.carNumber = carNum
        }
        mPresenter.dispatchModify(mClickHistoryInfo?.driverId, carId, mClickHistoryInfo?.waybillId, volume + "", isMo, mClickHistoryInfo?.isMultiple
                ?: false, times, deadLine, mClickHistoryInfo?.id)
    }

    override fun onModifyCarNumClick() {
        val intent = Intent(context, DispatchSearchActivity::class.java)
        intent.putExtra(ConstValue.TYPE, DispatchSearchActivity.SEARCH_TYPE_CARNUM)
        startActivityForResult(intent, REQUEST_CODE_MODIFY)
    }

    override fun onCarnumClick() {
        val intent = Intent(context, DispatchSearchActivity::class.java)
        intent.putExtra(ConstValue.TYPE, DispatchSearchActivity.SEARCH_TYPE_CARNUM)
        startActivityForResult(intent, REQUEST_CODE_AGAIN)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            var bundle: Bundle? = null
            if (data != null) {
                bundle = data.extras
            }
            if (bundle != null) {
                val carFreeBean = bundle.getSerializable("info") as CarFreeBean
                LogUtil.d("onActivityResult-" + carFreeBean.id + "--" + carFreeBean.carNum)
                when (requestCode) {
                    REQUEST_CODE_AGAIN ->

                        if (mDispatchAgainDialog != null && mDispatchAgainDialog?.isShowing == true) {
                            mDispatchAgainDialog?.setCarNum(carFreeBean.id, carFreeBean.carNum)
                        }

                    REQUEST_CODE_MODIFY -> {
                        LogUtil.d("onActivityResult-" + carFreeBean.id + "--" + carFreeBean.carNum)

                        if (mDispatchModifyDialog != null && mDispatchModifyDialog?.isShowing == true) {
                            mDispatchModifyDialog?.setCarNum(carFreeBean.id, carFreeBean.carNum)
                        }
                    }
                }
            }
        }
    }

    companion object {
        private const val REQUEST_CODE_AGAIN = 1000
        private const val REQUEST_CODE_MODIFY = 1001

        fun newInstance(id: Int, showOpera: Boolean): DispatchHistoryFragment {
            val args = Bundle()
            args.putInt(ConstValue.ID, id)
            args.putBoolean(ConstValue.SHOW_OPERA, showOpera)
            val homeFragment = DispatchHistoryFragment()
            homeFragment.arguments = args
            return homeFragment
        }
    }
}
